<?php

namespace backend\controllers;

use Yii;
use backend\models\SysHomeBanner;
use backend\models\SysHomeBannerSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use backend\models\Image;
use backend\models\SysItem;
use yii\web\ForbiddenHttpException;
use common\models\City;
use yii\db\Query;

/**
 * SysHomeBannerController implements the CRUD actions for SysHomeBanner model.
 */
class SysHomeBannerController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }
    public function beforeAction($action)
    {
    	//如果未登录，则直接跳转
    	if(Yii::$app->user->isGuest){
    		return $this->redirect(['/site/login']);
    	}
    
    
    	$action = Yii::$app->controller->action->id;
    	$controller = Yii::$app->controller->id;
    	if(\Yii::$app->user->can('homebanner-manage')){
    		return true;
    	}else{
    		throw new ForbiddenHttpException(Yii::t('app','Sorry , You don\'t have permission'));
    	}
    }
    /**
     * Lists all SysHomeBanner models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new SysHomeBannerSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single SysHomeBanner model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new SysHomeBanner model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new SysHomeBanner();

        if ($model->load(Yii::$app->request->post())) {
        	$img_url_id = '';
        	$img_thumb_id = '';
        	$img_small_id = '';
        	
        
        	     	
        		if($model->b_t_s_img_id == null)
        		{
        			if($model->big_img_id != null ) $img_url_id = $model->big_img_id;
        			if($model->thumb_img_id != null ) $img_thumb_id = $model->thumb_img_id;
        			if($model->small_img_id != null ) $img_small_id = $model->small_img_id;
        		}
        		else
        		{
        				
        			$url = Image::findOne($model->b_t_s_img_id)->url;
        			$model_image = new Image();
        			$_arr_img = $model_image->get_img_id($url);
        			$img_url_id = $_arr_img['big_img_id'];
        			$img_thumb_id = $_arr_img['thumb_img_id'];
        			$img_small_id = $_arr_img['small_img_id'];
        		}
        		$model->img_url_id = $img_url_id;
        		$model->img_thumb_id = $img_thumb_id;
        		$model->img_small_id = $img_small_id;
        		$model->create_time = time();
        		
        		if(!empty($model->province_id) || !empty($model->city_id)){
        			$province_id = $model->province_id; $city_id=$model->city_id;
        			$model->area = (in_array($province_id, array('110000','120000','310000','500000')))
        			? City::get_name($province_id) : City::get_name($province_id).' '.City::get_name($city_id);
        		}
        	if($model->save()){
           	 return $this->redirect(['view', 'id' => $model->id]);
        	}
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing SysHomeBanner model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post())) {
        	$img_url_id = '';
        	$img_thumb_id = '';
        	$img_small_id = '';
        	      	 
        	if($model->b_t_s_img_id == null)
        	{
        		if($model->big_img_id != null ) $img_url_id = $model->big_img_id;
        		if($model->thumb_img_id != null ) $img_thumb_id = $model->thumb_img_id;
        		if($model->small_img_id != null ) $img_small_id = $model->small_img_id;
        	}
        	else
        	{
        	
        		$url = Image::findOne($model->b_t_s_img_id)->url;
        		$model_image = new Image();
        		$_arr_img = $model_image->get_img_id($url);
        		$img_url_id = $_arr_img['big_img_id'];
        		$img_thumb_id = $_arr_img['thumb_img_id'];
        		$img_small_id = $_arr_img['small_img_id'];
        	}
        	if($img_url_id != null) $model->img_url_id = $img_url_id ;//如果有重新传入图片，则更新
        	if($img_thumb_id != null) $model->img_thumb_id = $img_thumb_id;
        	if($img_small_id != null) $model->img_small_id = $img_small_id;
        	$model->create_time = time();
        	
        	if($model->top_time_1 === '1'){$model->top_time = time();}//置顶
        	if($model->top_time_1 === '0'){$model->top_time = 0;}//不置顶
        	/*
        	if(!empty($model->province_id) || !empty($model->city_id)){
        		$province_id = $model->province_id; $city_id=$model->city_id;
        			$model->area = (in_array($province_id, array('110000','120000','310000','500000'))) 
        				? City::get_name($province_id) : City::get_name($province_id).' '.City::get_name($city_id);
        	}
        		*/
        	$area = array_filter($model->area);
        	$area = array_unique($area);
        	$area = array_values($area);

        	$count = count($area);
        	echo $count;
        	var_dump($area);
        	
        	$new_area = array();
        	if($count > 0){
        		$model->area = $area[0];
        		if($count > 1)
	        		for ($i=1;$i<$count;$i++){
	        			$one['banner_id']=$id;
	        			$one['area']=$area[$i];
	        			array_push($new_area, $one);
	        			//SysHomeBanner::more_area($id, $area[$i]);
	        		}  		
        	}else{
        		$model->area = '';
        	}
        	SysHomeBanner::more_area($new_area,$id);
        	if($model->save()){
            return $this->redirect(['view', 'id' => $model->id]);
        	}
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing SysHomeBanner model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the SysHomeBanner model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return SysHomeBanner the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
    	$area_more = array();
    	$area = array();
    	$model = SysHomeBanner::findOne($id);
        if ($model !== null) {
        	
        	$area_more = (new Query())->select('area')->from('sys_banner_area')->where("banner_id={$id}")->all();
        	$area[0] = $model->area;
   	
        	foreach ($area_more as $key => $val){	
        		if($val["area"] != '')
        			array_push($area, $val["area"]);
        	}
        	$model->area = $area;

            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    
    public function actionSelect_province_id($province_id){
    		
    	$result = City::select_province($province_id);
    	$option = '';
    
    	if ($result) {
    		foreach ($result as $value) {
    			$option .= '<option value="' . $value['id'] . '">' . $value['name'] . '</option>';
    		}
    	} else {
    		$option .= '<option value="0">暂无</option>';
    	}
    	echo $option;
    }
}
